<template>
  <!-- 提取明细   -->
    <div class="interestCalculationDetailsPage">
        <div class="search-wrap d-flex a-center j-end">
            <div class="search-buttons m-l50 d-flex a-center">
                <el-button
                        class="button_edit"
                        @click="startRepaymentPlan"
                >
                    发起还款计划
                </el-button>
                <el-button
                        class="button_edit"
                        @click="addAccrualPlan"
                >
                    新增计提计划
                </el-button>
                <el-button
                    class="button_edit"
                    @click="interestPaymentCalculation"
                >
                    利息支付计算
                </el-button>
                <el-button
                        class="button_edit"
                        @click="deleteDrawRecordList"
                >
                    删除
                </el-button>
                <el-button
                        class="button_edit"
                        @click="onExport"
                >
                    <svg-icon icon-class="project-detail-icon-derive" class="icon-export m-r5"></svg-icon>
                    一键导出
                </el-button>
            </div>
        </div>
            <public-table
                ref="publicTableRef"
                class="m-t20"
                index
                radio
                :indexWidth="'100'"
                :page="page"
                :tableData="tableData"
                :tableOption.sync="tableOption"
                @page-change="onPageChange"
                @handleSelectionChange="handleSelectionChange"
            >
                <template #update="scope">
                    <el-button v-if="!scope.row.isEdit" @click="onEdit(scope.row)" class="button_edit">编辑</el-button>
                    <div v-else>
                        <el-button @click="onSave(scope.row)" class="button_view">保存</el-button>
                        <el-button @click="onCancel(scope.row)" class="button_cancel2">取消</el-button>
                    </div>
                </template>
                <template #lastInterestRate="scope">
                    <span v-if="!scope.row.isEdit">{{scope.row.lastInterestRate}}</span>
                    <el-input v-else v-model="scope.row.lastInterestRate"></el-input>
                </template>
                <template #plannedRepaymentTime="scope">
                    <span v-if="!scope.row.isEdit">{{scope.row.plannedRepaymentTime}}</span>
                    <el-date-picker
                        v-else
                        v-model="scope.row.plannedRepaymentTime"
                        type="date"
                        placeholder="Pick a day"
                        size="large"
                        style="width: 90px;"
                    />
                </template>
                <template #interestRateUpdateTime="scope">
                    <span v-if="!scope.row.isEdit">{{scope.row.interestRateUpdateTime}}</span>
                    <el-date-picker
                        v-else
                        v-model="scope.row.interestRateUpdateTime"
                        type="date"
                        placeholder="Pick a day"
                        size="large"
                        style="width: 90px;"
                    />
                </template>
                <template #currentInterestRate="scope">
                    <span v-if="!scope.row.isEdit">{{scope.row.currentInterestRate}}</span>
                    <el-input v-else v-model="scope.row.currentInterestRate"></el-input>
                </template>
            </public-table>
    </div>

    <public-dialog
            :title="'新增计提计划'"
            :width="'60%'"
            :confirmButtonTitle="'确认'"
            v-model:visible="visible"
            @onConfirm="onConfirm"
    >
        <div class="public-dialog-content d-flex flex-column">
            <el-form
                ref="financingFormRef"
                :model="extractDetailsForm"
                :rules="extractDetailsRules"
                label-width="150"
                v-if="selectedArr.length!==0"
            >
                <label class="d-flex m-b20">借款信息</label>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="借款单位">
                           <el-input disabled :placeholder="selectedArr[0].companyName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="金融机构">
                            <el-input disabled :placeholder="selectedArr[0].institutionName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="担保方式">
                            <el-input
                                disabled
                                :placeholder="['','信用','担保','抵押','质押'][selectedArr[0].guaranteeType] || '-'"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="贷款用途">
                            <el-input disabled :placeholder="selectedArr[0].loanPurpose"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="授信时间">
                            <el-input disabled :placeholder="selectedArr[0].creditTime"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="贷款余额">
                            <el-input disabled :placeholder="selectedArr[0].loanBalance"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-divider></el-divider>
                <label class="d-flex m-b20">利息信息</label>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="最新利率">
                            <el-input disabled :placeholder="selectedArr[0].currentInterestRate"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="调整当日利率">
                            <el-input disabled :placeholder="selectedArr[0].lastInterestRate"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="年利率调整日期">
                            <el-input disabled :placeholder="selectedArr[0].interestRateUpdateTime"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">

                    </el-col>
                </el-row>
                <el-divider></el-divider>
                <label class="d-flex m-b20">计提信息</label>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="计提时间" prop="startTime">
                            <el-date-picker
                                size="large"
                                v-model="extractDetailsForm.time"
                                type="daterange"
                                range-separator="-"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                @change="timeChange"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">

                    </el-col>
                </el-row>
            </el-form>
        </div>
    </public-dialog>

    <interest-payment-calculation-popup
        ref="interestPaymentCalculationPopupRef"
        @on-success="onSuccess"
    />
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {
    ElForm,
    ElFormItem,
    ElRow,
    ElCol,
    ElDatePicker,
    ElMessage, ElDivider
} from "element-plus";
import PublicTable from "@/components/PublicTable.vue";

import {tableCommonFun} from "@/hooks/tableCommon";
import {financingApi} from "@/api/businessFinance";
import PublicDialog from "@/components/PublicDialog.vue";
import {useRouter} from "vue-router";
import InterestPaymentCalculationPopup from "./components/interestPaymentCalculationPopup"

const router = useRouter();
const id = router.currentRoute.value.params.id;

const interfaceConfig = reactive({
    fileName:'businessFinance',
    apiPath:'financingApi.getBankLoanDrawRecordVo',
});
const exportConfig = reactive({
    fileName:'',
    apiPath:'',
    tableName:''
});
const {
    form,
    page,
    tableOption,
    tableData,
    getData,
    onExport
}  = tableCommonFun(interfaceConfig,exportConfig);

form.value = {
   id:''
}

tableOption.value = [
    { label: "公司名称 ", prop: "companyName" },
    { label: "金融机构 ", prop: "institutionName" },
    { label: "贷款时间 ", prop: "loanTime" },
    { label: "计划还款时间 ", prop: "plannedRepaymentTime",slot:true,width:'120',overHidden:false},
    { label: "上一年度利率 ", prop: "lastInterestRate",slot:true,width:'120' },
    { label: "贷款用途 ", prop: "loanPurpose" },
    { label: "提取时间 ", prop: "drawTime" },
    { label: "提取金额 ", prop: "drawAmount" },
    { label: "借款余额 ", prop: "loanBalance" },
    { label: "年利率调整日 ", prop: "interestRateUpdateTime",slot:true,width:'120' },
    { label: "当前利率 ", prop: "currentInterestRate",slot:true },
    { label: "担保类型 ", prop: "guaranteeType",formatter:(val,row)=>{
            return ['','信用','担保','抵押','质押'][val] || '-';
        } },
    { label: "操作 ", prop: "update",slot:true,width:'150',fixed:'right' },

];

const extractDetailsForm = reactive({
    startTime:'',
    endTime:'',
    time:''
});

const extractDetailsRules = reactive({
    startTime: [
        { required: true, message: '请选择计提时间', trigger: 'change' },
    ]
});

/**
 * 新增融资信息
 */
const addBankCreditAmount = (param,callback) => {
    financingApi.addBankCreditAmount(param).then(res=>{
        if(res.code === '200'){
            if(callback)callback(res);
        }
    })
}

/**
 * 新增融资信息确认
 *
 */
const financingFormRef = ref(null);
const onConfirm = () => {
    financingFormRef.value.validate((valid, fields) => {
        if (valid) {
            let params = {
                creditId:id,
                ...extractDetailsForm,
                ...selectedArr.value[0]
            }
            financingApi.addBankLoanInterest(params).then(res=>{
                if(res.code === '200'){
                    getData({
                        pageNum:1,
                        pageSize:10,
                        param:id
                    });
                    visible.value = false;
                    publicTableRef.value.clearSelection();
                    selectedArr.value = [];
                    ElMessage.success('新增计提计划成功!');
                    router.push({path:`/businessFinance/bankManagement/interestManagement/accruedPayable`});
                }
            });
        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * 页面改变时触发
 */
const onPageChange = (e) => {
    page.current = e.page;
    page.size = e.limit;
    let param = {
        param: form.value.id,
        pageNum: page.current,
        pageSize: page.size,
    };
    getData(param);
}

/**
 * public-table 被选中时触发
 * @param arr
 */
const selectedArr = ref([]);
const handleSelectionChange = (arr) => {
    selectedArr.value = arr;
}

/**
 * 发起还款计划
 */
const publicTableRef = ref(null);
const startRepaymentPlan = () => {
    if(selectedArr.value.length===0){
        ElMessage.warning('请选择要操作的数据!');
        return;
    }
    financingApi.initiateRepaymentPlan({
        ...selectedArr.value[0]
    }).then(res=>{
       if(res.code === '200'){
           selectedArr.value = [];
           publicTableRef.value.clearSelection();
           ElMessage.success('发起还款计划成功!');
           visible.value = false;
       }
    });
}

/**
 * 新增计提计划按钮
 */
const visible = ref(false);
const addAccrualPlan = () => {
    if(selectedArr.value.length===0){
        ElMessage.warning('请选择要操作的数据!');
        return;
    }
    visible.value = true;
}

/**
 * 选择计提时间时触发
 * @param e
 */
const timeChange = (e) => {
    if(e===null || (e instanceof Array && e.length===0)){
        extractDetailsForm.startTime = '';
        extractDetailsForm.endTime = '';
        return;
    }
    extractDetailsForm.startTime = e[0];
    extractDetailsForm.endTime = e[1];
}

/**
 * 删除提取明细
 */
const deleteDrawRecordList = () => {
    if(selectedArr.value.length===0){
        ElMessage.warning('请选择要删除的数据!');
        return;
    }
    financingApi.deleteDrawRecordList({
        list:[selectedArr.value[0].drawRecordId]
    }).then(res=>{
        if(res.code === '200'){
            ElMessage.success('删除成功!');
            selectedArr.value = [];
            publicTableRef.value.clearSelection();
            getData({
                pageNum:1,
                pageSize:10,
                param:id
            });
        }
    });
}

/**
 * 编辑按钮
 * @param row
 */
const onEdit = (row) => {
    row.isEdit = true;
}

/**
 * 保存
 * @param row
 */
const onSave = (row) => {
    if(row.plannedRepaymentTime===''){
        ElMessage.warning('计划还款时间不能为空!');
        return;
    }
    if(row.lastInterestRate===''){
        ElMessage.warning('上一年度利率不能为空!');
        return;
    }
    if(row.interestRateUpdateTime===''){
        ElMessage.warning('年利率调整日不能为空!');
        return;
    }
    if(row.currentInterestRate===''){
        ElMessage.warning('当前利率不能为空!');
        return;
    }
    financingApi.updateBankLoanDrawRecord({
        drawRecordId: row.drawRecordId,
        plannedRepaymentTime: row.plannedRepaymentTime,
        lastInterestRate: row.lastInterestRate,
        interestRateUpdateTime: row.interestRateUpdateTime,
        currentInterestRate: row.currentInterestRate
    }).then(res=>{
       if(res.code === '200'){
           ElMessage.success('编辑成功!');
           row.isEdit = false;
       }else{
           const callback = (res) => {
               res.data.content.forEach(item=>{
                   item.isEdit = false;
               })
           }
           getData({
               pageNum:page.current,
               pageSize:page.size,
               param:id
           },callback);
       }
    });
}

/**
 * 取消
 * @param row
 */
const onCancel = (row) => {
   row.isEdit = false;
}

/**
 * 利息支付计算
 */
const interestPaymentCalculationPopupRef = ref(null);
const interestPaymentCalculation = () => {
    if(selectedArr.value.length===0){
        return ElMessage.warning('请选择要操作的数据!');
    }
    interestPaymentCalculationPopupRef.value.open(selectedArr.value[0]);
}

/**
 * 弹窗成功后
 */
const onSuccess = () => {
    const callback = (res) => {
        res.data.content.forEach(item=>{
            item.isEdit = false;
        })
    }
    getData({
        pageNum:1,
        pageSize:10,
        param:id
    },callback);
    router.push({path:`/businessFinance/bankManagement/interestManagement/interestPayment`});
}

onMounted(()=>{
    form.value.id = id;
    const callback = (res) => {
        res.data.content.forEach(item=>{
            item.isEdit = false;
        })
    }
    getData({
        pageNum:1,
        pageSize:10,
        param:id
    },callback);
});
</script>

<style lang="scss" scoped>
.interestCalculationDetailsPage{
  .el-input-width{
    width: 243px !important;
  }
  .search-wrap{
    .search-item{

      .el-input{
        width: 243px !important;
      }
    }
    .search-buttons{
      .icon-export{
        width: 18px;
        height: 18px;
      }
    }
  }
}
.public-dialog-content{
  .dialog-title-box{
    height: 30px;
    span{
      font-size: 15px;
      font-weight: 600;
    }
  }
}
</style>
